package com.example.demo.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.UsersInfo;
import com.example.demo.service.IUsersInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
 *
 *   @Author: Sjy
 *   @Date: 2024/3/25-03-25-19:05
 *   用于建立长连接的类
 */
@Component
//定义此类是WS的服务器端
@ServerEndpoint("/private/chat/{userId}")
public class WebSocketServer {

    //ws一共有四种状态
    private static Map<String,SocketUserInfo> map = new HashMap<>();
    //利用静态变量只会实例一次
    private static IUsersInfoService iUsersInfoService;
    @Autowired
    public void setIUsersInfoService(IUsersInfoService iUsersInfoService){
        this.iUsersInfoService = iUsersInfoService;
    }

    /**
     * 连接建立成功时触发
     * @param session 当前会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String userId){
        UsersInfo usersInfo = iUsersInfoService.getById(userId);
        //在put放了一个对象SocketUserInfo 一个是这个人的昵称，一个是session
        SocketUserInfo socketUserInfo = new SocketUserInfo(usersInfo.getNickname(), session);
        map.put(userId, socketUserInfo);
        System.out.println(socketUserInfo.toString()+"成功的建立了连接");
    }
    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(@PathParam("userId")String userId){
        map.remove(userId);
    }
    /**
     * 收到客户端消息时触发
     * @param message
     */
    @OnMessage
    public void onMessage(String message, @PathParam("userId")String userId){
        //解析message，获取msg和id 格式是{"msg":"1111111111","id":"1"}
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String msg = jsonObject.getStr("msg");
        String id = jsonObject.getStr("id");
        //通过id获取到map对象里面的session
        Session session = map.get(id).getSession();
        //谁说了什么
        UsersInfo usersInfo = iUsersInfoService.getById(userId);
        JSONObject json1 = JSONUtil.createObj()
                .put("nickName", usersInfo.getNickname())
                .put("msg", msg);
        //单聊
        try {
            //通过session长连接隧道给前端推送信息
            session.getBasicRemote().sendText(json1.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 群聊遍历map
        /*Set set = map.keySet();
        for (Object o : set) {
            SocketUserInfo socketUserInfo = map.get(o);
            try {
                socketUserInfo.getSession().getBasicRemote().sendText(json1.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/

    }

    /**
     * 发生错误时触发
     * @param error
     */
    @OnError
    public void onError(Throwable error,@PathParam("userId")String userId){
        map.remove(userId);
    }
}
